<?php
/** 
 * Created by RisingSun. 
 * User: MarkSpace 
 * Date: 20210822
 * Time: 11:05 
 * 列表管理
 */
namespace app\finance\model;

use  app\finance\model\Model;
use  app\finance\model\Common;

class Withdraw extends Model{
    
    private $account = 'user_account'; // 账户表
    private $cert = 'user_cert'; // 账户表
    private $withdraw = 'user_withdraw'; // 兑换表
    

    // private $error=['code'=>0,'msg'=>'fail'];
    // private $success=['code'=>200,'msg'=>'success']; 

    /**
     * 提现列表
     * @param array $apply 
     * @param array $where 
     */ 
    public function withdraw($where=null,$page=1,$page_size=10){
        //列表
        $list['datalist']= Model::name($this->withdraw)
            ->alias('a')
            ->join($this->account.' b','a.aid=b.aid','left')
            ->field('a.*,b.realname,b.username')
            ->where($where)
            ->limit(($page-1)*$page_size,$page_size)
            ->order('a.status asc, a.id desc')
            ->select();
        foreach ($list['datalist'] as $key => $value) {
          
        }
        //数据总数
        $list['total']=Model::name($this->withdraw)
            ->alias('a')
            ->join($this->account.' b','a.aid=b.aid','left')
            ->where($where)
            ->count('a.id');
        return $list;
    }

    /**
     * 提现信息
     * @param array $applyinfo 
     * @param array $where 
     */ 
    public function drawinfo($id=null){  
        $info=Model::name($this->withdraw)
           ->alias('a')
           ->join($this->account.' b','a.aid=b.aid','left')
           ->join($this->cert.' c','a.aid=c.aid','left')
           ->field('a.*, b.realname,b.mobile,b.username,b.email, c.bankaccount')
           ->where(['a.id'=>$id])
           ->find();
        if(isset($info['bankaccount'])){
            $info['bankaccount']=!empty($info['bankaccount'])&&isJson($info['bankaccount'])?json_decode($info['bankaccount'],true):[];
        }
        return $info;
    }

    /**
     * 提现保存
     * @param array $save 
     * @param array $where 
    */ 
    public function save($data,$operator=[]){
        //保存
        $updata=[
            'amount'=>$data['amount'],
            'integra'=>$data['integra'],
        ];
       $data  = [
            'aid'=>$data['aid'],
            'payment'=>$data['payment'],
            'type'=>$data['type'],
            'money'=>$data['money'],
            'remoney'=>$data['remoney'],
            'integra'=>round(($data['integras']-$data['integra'])*100)/100,
            'reintegra'=>round(($data['integras']-$data['integra'])*$data['rate']*100)/100,
            'fee'=>$data['fee'],
            'currency'=>$data['currency'],
            'codes'=>$data['codes'],
            'rate'=>$data['rate'],
            'file_url'=>$data['file_url'],
            'status'=>$data['status'],
            'createtime'=>date('Y-m-d H:i:s',time())
        ];
        //获取账户资金
        $user=(new Common())->getAccount('aid='.$data['aid'],['username','amount','integra','cash','pid']);
        $data['pid']=$user['pid'];
        //通过
        Model::startTrans();
        try{
            switch ($data['type']) {
                case 2: //付款
                    $data['money']=round(($data['money']-$data['fee'])*100)/100;
                    $data['remoney']=round(($data['money']*$data['rate'])*100)/100;
                    $updata['cash']=$data['money'];
                    (new Common())->updateAccount('aid='.$data['aid'],$updata);
                    logrecord(
                        '付款账户id'.$data['aid'].';付款账户'.$user['username'].';账户金额：'.$user['amount'].';赠送金额:'.$user['integra'].';付款金额：'.$data['money'].';手续费：'.$data['fee'],
                        $operator,
                        'withdraw/'
                    );
                    break;
                case 3:  //扣款
                    $data['fee']=0;
                    (new Common())->updateAccount('aid='.$data['aid'],$updata);
                    logrecord(
                        '扣款账户id'.$data['aid'].';扣款账户'.$user['username'].';账户金额：'.$user['amount'].';赠送金额:'.$user['integra'].';扣款金额：'.$data['money'].';手续费：'.$data['fee'],
                        $operator,
                        'withdraw/'
                    );
                    break;
            }
            Model::name($this->withdraw)->insert($data);
            Model::commit();
            return true;
        }catch (Exception $e){
            Model::rollback();
            return false;
        }
        return false;
    }

    /**
     * 充值審核
     * @param array $examine 
     * @param array $where 
    */ 
    public function examine($data, $operator=[]){
        $id=$data['id'];
        //保存
        $data  = [
            'aid'=>$data['aid'],
            'type'=>$data['type'],
            'money'=>$data['money'],
            'fee'=>$data['fee'],
            'integra'=>$data['integra'],
            'payment'=>$data['payment'],
            'notes'=>$data['notes'],
            'status'=>$data['status'],
            'updatetime'=>date('Y-m-d H:i:s')
        ];
        Model::startTrans();
        try {
            $user=(new Common())->getAccount('aid='.$data['aid'],'amount,integra,cash,username,fee');
            switch ($data['status']) {
                case 3:
                    $updata=[
                        'cash'=>$user['cash']+$data['money'],
                        'fee'=>$user['fee']+$data['fee']
                    ];
                    if($data['type']<3){
                        (new Common())->updateAccount('aid='.$data['aid'],$updata);
                    }
                    logrecord(
                        '记录id'.$id.';账户'.$user['username'].';金额：'.$user['amount'].';赠送:'.$user['integra'].';交易金额：'.$data['money'].';手续费：'.$data['fee'].';审核状态：通过',
                        $operator,
                        'withdraw/'
                    );
                    break;
                case 2:
                    $updata=[
                        'amount'=>($user['amount']+$data['money']-$data['integra']),
                        'integra'=>($user['integra']+$data['integra'])
                    ];
                    (new Common())->updateAccount('aid='.$data['aid'],$updata);
                    logrecord(
                        '记录id'.$id.';账户'.$user['username'].';金额：'.$user['amount'].';赠送:'.$user['integra'].';交易金额：'.$data['money'].';手续费：'.$data['fee'].';审核状态：退回',
                        $operator,
                        'withdraw/'
                    );
                    break;
                default:
                    logrecord(
                        '记录id'.$id.';账户'.$user['username'].';金额：'.$user['amount'].';赠送:'.$user['integra'].';交易金额：'.$data['money'].';手续费：'.$data['fee'].';审核状态：无审核',
                        $operator,
                        'withdraw/'
                    );
                    break;
            }
            unset($data['aid'],$data['money'],$data['fee']);
            Model::name($this->withdraw)->where('id=' . $id)->update($data);
            Model::commit();
            return true;
        } catch (Exception $e) {
            Model::rollback();
            return false;
        }
        return false;
    }

}